package com.big.pay.listener;

import com.big.common.result.Result;
import com.big.common.utils.JsonUtils;
import com.big.model.model.record.MerchandiseOrderRecord;
import com.big.model.model.stock.MerchandiseStock;
import com.big.model.vo.stock.StockVo;
import com.big.order.OrderFeignClient;
import com.big.pay.config.RabbitConfig;
import com.big.stock.StockFeignClient;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.xml.bind.util.JAXBSource;
import java.util.List;

@Component
public class StockListener {



    @Autowired
    OrderFeignClient orderFeignClient;

    @Autowired
    StockFeignClient stockFeignClient;

    @RabbitListener(queues=RabbitConfig.QUEUE_STOCK_ITEM)
    public void OnStock(String oId ){
        Result result = orderFeignClient.MerchandiseOrderRecords(oId);

        String StringInfo = JsonUtils.ObjectTurnString(result.getData());
        List<MerchandiseOrderRecord> merchandiseOrderRecordList = JsonUtils.jsonToList(StringInfo, MerchandiseOrderRecord.class);

        merchandiseOrderRecordList.forEach(item -> {
           this.UpStock(item);
        });

    }

    /**
     * 改变仓库
     */
    public void UpStock(MerchandiseOrderRecord merchandiseOrderRecord){
        //当前的仓库
        MerchandiseStock merchandiseStock = this.InfoMerchandiseStock(merchandiseOrderRecord);
        //仓库已售
        Integer sSold = merchandiseStock.getSSold();
        //仓库剩存
        Integer sNum = merchandiseStock.getSNum();

        StockVo stockVo=new StockVo();
        //已购数量
        Integer mNum = merchandiseOrderRecord.getMNum();
        stockVo.setSNum(sNum-mNum);
        stockVo.setSSold(sSold+mNum);
        stockVo.setMId(String.valueOf(merchandiseStock.getMId()));
        stockFeignClient.stockChange(stockVo);

    }

    /**
     * 查询仓库
     */

    public MerchandiseStock InfoMerchandiseStock(MerchandiseOrderRecord merchandiseOrderRecord) {
        Result information = stockFeignClient.Information(String.valueOf(merchandiseOrderRecord.getMId()));
        String StringInfo = JsonUtils.ObjectTurnString(information.getData());
        //转对象
        MerchandiseStock merchandiseStock = JsonUtils.JSONStringInfoTurnClass(StringInfo, MerchandiseStock.class);
        return merchandiseStock;
    }

}
